//
//  CloudApiService+Sign.swift
//  Health-Doctor
//
//  Created by woniu on 2025/8/1.
//  Copyright © 2025 掌上卫健. All rights reserved.
//

import Foundation

//签约模块
extension CloudApiService{
    
    /// 查询签约详情
    /// - Parameters:
    ///   - searchKey: 关键词，一般用身份证
    ///   - finish: 回调
    public func httpGetWebSignDetail(searchKey:String,rhrId:String,finish:@escaping((_ re:Bool,_ detail:ContractDetailModel?)->())){
        let block = {
            //从云平台网页拿数据
            self.aipSearchListBy(searchKey: searchKey,signStatus: .didSign, areaId: self.areaId, token: self.token, uuid: self.uuid) {[weak self] re, detail in
                guard let `self` = self else { return }
                if re{
                    if !detail.isEmpty{
                        var dataParam = detail
                        //替换档案ID
                        dataParam["daId"] = rhrId
                        self.httpSignCloudToWoniuData(cloudSignDetail: dataParam) {re2, woniuDetail in
                            if re2{
                                let model = ContractDetailModel.deserialize(from: woniuDetail)
                                finish(true,model)
                            }else{
                                finish(false,nil)
                            }
                        }
                    }else{
                        finish(true,nil)
                    }
                }else{
                    finish(false,nil)
                }
            }
        }
        if sid.isEmpty || token.isEmpty{
            self.printWrite(log: "查询签约详情，发现未登录，去登录")
            self.onLoginSuccessBlock = block
            self.reAutoLogin()
        }else{
            block()
        }
    }
    
    
    /// 云平台签约详情转蜗牛签约详情
    /// - Parameters:
    ///   - cloudSignDetail: 云平台签约详情
    ///   - rhrId: 档案ID
    ///   - finish: 返回蜗牛格式的签约详情
    private func httpSignCloudToWoniuData(cloudSignDetail:[String:Any],finish:@escaping((_ re:Bool,_ woniuDetail:[String:Any])->())){
        let action = SignAction.cloudSignToWoniuDetail(param: cloudSignDetail)
        signProvider.httpRequst(action) { result in
            if result.isSuccess(){
                let signDetail = result.dicData()
                finish(true,signDetail)
                
            }else{
                MyMessage.showText(message: result.msg)
                finish(false,[:])
            }
        }
    }
    
    
    /// 解约
    /// - Parameters:
    ///   - param: 参数
    public func httpSign_relieve(contractId:String,reason:String,finish:@escaping((_ re:Bool)->())){
        let block = {
            //从云平台网页拿数据
            self.apiSignRelieve(contractId: contractId, reason: reason, token: self.token, sid: self.sid, uuid: self.uuid, finish: finish)
        }
        if sid.isEmpty || token.isEmpty{
            self.printWrite(log: "解约时，发现未登录，去登录")
            self.onLoginSuccessBlock = block
            self.reAutoLogin()
        }else{
            block()
        }
    }
}

//云平台网页签约状态
enum CloudSignStatusEnum: String {
    //已签约
    case didSign = "1"
    //未签约
    case notSign = "-1"
    //已过期
    case expire = "2"
}
//签约模块
extension CloudApiService{
    
    private func aipSearchListBy(searchKey:String,signStatus:CloudSignStatusEnum,areaId:String,token:String,uuid:String,finish:@escaping((_ re:Bool,_ detail:[String:Any])->())){
        let ipAddress = getIpAddress()
        var components = URLComponents(string: "\(ipAddress)/ehrc/familydoctor/contract/list/detail")!
        
        components.queryItems = [
            URLQueryItem(name: "isHistory", value: "no"),
            URLQueryItem(name: "keyword", value: searchKey),
            URLQueryItem(name: "contractStatus", value: signStatus.rawValue),
            URLQueryItem(name: "agentUserId", value: ""),
            URLQueryItem(name: "cuser", value: ""),
            URLQueryItem(name: "dueDateOfDay", value: ""),
            URLQueryItem(name: "orderColumn", value: ""),
            URLQueryItem(name: "fxdj", value: ""),
            URLQueryItem(name: "peopleTags", value: ""),
            URLQueryItem(name: "daztCode", value: "10"),
            URLQueryItem(name: "jgId", value: ""),
            URLQueryItem(name: "qhId", value: areaId),
            URLQueryItem(name: "isIncludePackDetail", value: "true"),
            URLQueryItem(name: "showQuickJumper", value: "true"),
            URLQueryItem(name: "total", value: "127"),
            URLQueryItem(name: "showSizeChanger", value: "true"),
            URLQueryItem(name: "current", value: "1"),
            URLQueryItem(name: "defaultPageSize", value: "10"),
            URLQueryItem(name: "pageSize", value: "10"),
            URLQueryItem(name: "size", value: "big")
        ]
        
        guard let url = components.url else {
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.setValue("swLlXAR2OP9NCd6fAyE8v6kms8Ty10E5BKlEKExwrfmMvcQPXMND9Archy6ONaZ9EGZ4g0mzEyjeJDTyn0ru8UbBYabHZnNHda7hKNFQ/A6RO0ajT20+RXxcFOD3bOqabmU5lP/VU+iPdZziRduuS7EIpEn7jR8mL9Czunl/BP7PxSRZfei5OLjeB1AjdlrvPuEbiqh3IDIe1TqdTM/4ylOx0bGZZQjwvkNBqybsaxs=", forHTTPHeaderField: "Jom-Rjkmj-Jrjm")
        request.setValue("TixImo5tJADvP3HB", forHTTPHeaderField: "Lsq-Zkdor-Lwql")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("\(ipAddress)/jtys.html", forHTTPHeaderField: "Referer")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        
        let cookie = "token=\(token); sid=\(sid); uuid=\(uuid)"
        request.setValue(cookie, forHTTPHeaderField: "Cookie")
        
        request.writeToLogFile()
        
        // 创建并启动任务
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    
                    self.printWrite(log: "通过关键词\(searchKey)/\(signStatus.rawValue)搜索签约列表返回->\(responseString)")
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataArray = dic.dictionary("data").array("data")
                        LogUtil.print(info: "查询到数据")
                    
                        //已签约的未查到，则查询已过期的
                        if dataArray.isEmpty && signStatus == .didSign{
                            self.aipSearchListBy(searchKey: searchKey, signStatus: .expire, areaId: self.areaId, token: self.token, uuid: self.uuid, finish: finish)
                            
                        }else{
                            //查询详情
                            if let fristData = dataArray.first{
                                let contractId = fristData.strValue("contractId")
                                self.apiGetSignDetail(contractId: contractId, token: self.token, uuid: self.uuid, sid: self.sid, finish: finish)
                            }else{
                                finish(true,[:])
                            }
                        }
                        
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        if self.isLoginExpiry(msg: httpErrorMsg) == true{
                            let log = "获签约详情接口aipGetSignDetail发现登录过期 error:\(httpErrorMsg)）准备重新登录，登录成功后需重新调用该接口"
                            self.printWrite(log: log)
                            self.onLoginSuccessBlock = {[weak self]in
                                guard let `self` = self else { return }
                                self.aipSearchListBy(searchKey: searchKey,signStatus: signStatus, areaId: self.areaId, token: self.token, uuid: self.uuid,finish: finish)
                            }
                        }else{
                            finish(false,[:])
                        }
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                    }
                    
                }
                
            }
            
        }
        task.resume()
        
    }
    
    
    /// 获取签约详情
    /// - Parameters:
    ///   - contractId: 数据ID
    ///   - orgId: 机构ID
    ///   - token: TOKEN
    ///   - uuid:
    ///   - sid:
    private func apiGetSignDetail(contractId:String,token:String,uuid:String,sid:String,finish:@escaping((_ re:Bool,_ signDetail:[String:Any])->())) {
        
        let ipAddress = getIpAddress()
        let urlString = "\(ipAddress)/ehrc/familydoctor/contract/\(contractId)/detail?"
        guard let url = URL(string: urlString) else {
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.setValue(getAgbBatbaBbabString(), forHTTPHeaderField: "Agb-Batba-Bbab")
        request.setValue("", forHTTPHeaderField: "accessToken2")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("\(ipAddress)/index.html", forHTTPHeaderField: "Referer")
        request.setValue("KZEiL1Fncf64VB2N", forHTTPHeaderField: "E5o-Vt3gb-1aom")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("token=\(token); sid=\(sid); uuid=\(uuid)", forHTTPHeaderField: "Cookie")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        
        
        request.writeToLogFile()
        
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "签约详情接口apiGetSignDetail返回->\(responseString)")
                    
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let cloudData = dic.dictionary("data")
                        finish(true,cloudData)
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false,[:])
                    }
                    
                }else{
                    MyMessage.showText(message: "操作失败，请重试")
                    finish(false,[:])
                }
                
            }
            
        }
        task.resume()
    }
    
    
    /// 解约
    /// - Parameters:
    ///   - param: 签约数据
    public func apiSignRelieve(contractId:String,reason:String,token:String,sid:String,uuid:String,finish:@escaping((_ re:Bool)->())){
        let params:[String:Any] = ["cancelReason":reason,"contractIds":[contractId],"_modulePartId_":"2e69baa678fa45cfab041bd3ea33b4e7"]
        let ipAddress = getIpAddress()
        let cancelContractPath = "\(ipAddress)/ehrc/familydoctor/contract/cancel"
        guard let url = URL(string: cancelContractPath) else {
            return
        }
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = "PUT"
        urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        urlRequest.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        urlRequest.setValue(token, forHTTPHeaderField: "accessToken")
        urlRequest.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        urlRequest.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        urlRequest.setValue("keep-alive", forHTTPHeaderField: "Connection")
        urlRequest.setValue(ipAddress, forHTTPHeaderField: "Origin")
        urlRequest.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        urlRequest.setValue("\(ipAddress)/jtys.html", forHTTPHeaderField: "Referer")
        urlRequest.setValue("u=3, i", forHTTPHeaderField: "Priority")
        
        // 添加自定义头部
        urlRequest.setValue("t2pBX9JxM0+RLYSkmOn5OfpG/vVghI6wTizHjZA4uDrO+eK6/LsqYPYDAM6OdN2WK9dZgcY3K7tkyn0lErIzVwPlGhuRtzQIgrZwegqa6cJvhP0VH7C78k2gxhgrR5XN2x78WjzNya0gS5TgeRa7t02c4/rhbDfa3vrO1F9grAnYHpFiElEDOod8HhwjPaaH2MuepGFNou9Vqz62kGDneu8j4D5O/TUwawyc+blAlIg=", forHTTPHeaderField: "Ehx-Ogyxg-Soex")
        urlRequest.setValue("2lW1SyoinMs8RfwE", forHTTPHeaderField: "Mld-Oolaa-Bocp")
        let cookie = "token=\(token); sid=\(sid); uuid=\(uuid)"
        urlRequest.setValue(cookie, forHTTPHeaderField: "Cookie")
        
        if let jsonData = try? JSONSerialization.data(withJSONObject: params){
            urlRequest.httpBody = jsonData
        }
        urlRequest.writeToLogFile()
        
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: urlRequest) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "解约接口返回->\(responseString)")
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        finish(true)
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false)
                    }
                }else{
                    MyMessage.showText(message: "保存失败，请重试")
                    finish(false)
                }
            }
            
        }
        task.resume()
    }
}
